package cn.com.xinjinfu.pdoulcProduct.activity.user;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import cn.com.xinjinfu.pdoulcProduct.R;
import cn.com.xinjinfu.pdoulcProduct.activity.base.BaseActivity;
import cn.com.xinjinfu.pdoulcProduct.activity.login.CheckMobileActivity;
import cn.com.xinjinfu.pdoulcProduct.engine.DataHandler;
import cn.com.xinjinfu.pdoulcProduct.entity.User;
import cn.com.xinjinfu.pdoulcProduct.manager.AccountManager;
import cn.com.xinjinfu.pdoulcProduct.manager.ActivityManager;
import cn.com.xinjinfu.pdoulcProduct.manager.JSONManager;
import cn.com.xinjinfu.pdoulcProduct.manager.L;
import cn.com.xinjinfu.pdoulcProduct.manager.TitleManager;
import cn.com.xinjinfu.pdoulcProduct.manager.ToastManager;
import cn.com.xinjinfu.pdoulcProduct.manager.UIManager;
import cn.com.xinjinfu.pdoulcProduct.utils.SharedPreferencesUtils;

/**
 * 修改登录密码
 * Created by android-adt on 2016/3/7.
 */
public class ActivityChangPsword extends BaseActivity {

    public TextView tv_error_hint1, tv_error_hint2;
    public EditText et_pw, et_set_pw, et_set_pw2;
    private RequestQueue requen;
    private Button register_bt;
    private String passwd, passwd1, oldPasswd;
    private Dialog dg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_chang_psword);
        //初始化头布局
        TitleManager.showTitle(this, "修改密码", "");
        ActivityManager.getInstance().addActivity(this);
        requen = Volley.newRequestQueue(this);
        et_pw = (EditText) findViewById(R.id.et_pw);
        et_set_pw = (EditText) findViewById(R.id.et_set_pw);
        et_set_pw2 = (EditText) findViewById(R.id.et_set_pw2);
        et_pw.addTextChangedListener(mTextWatcher);
        et_set_pw.addTextChangedListener(mTextWatcher);
        et_set_pw2.addTextChangedListener(mTextWatcher);
        tv_error_hint1 = (TextView) findViewById(R.id.tv_error_hint1);
        tv_error_hint2 = (TextView) findViewById(R.id.tv_error_hint2);
        register_bt = (Button) findViewById(R.id.register_bt);
        register_bt.setEnabled(false);
        register_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                oldPasswd = et_pw.getText().toString();
                passwd = et_set_pw.getText().toString();
                passwd1 = et_set_pw2.getText().toString();

                if (!oldPasswd.equals("")) {
                    if (!passwd.equals(passwd1)) {
                        tv_error_hint2.setVisibility(View.VISIBLE);
                        tv_error_hint2.setText("两次密码不一致!");
                    } else {
                        loginRequest("1");
                    }
                }else {
                    tv_error_hint1.setVisibility(View.VISIBLE);
                    tv_error_hint1.setText("原始密码不能为空！");
                }
            }
        });
    }

    /**
     * 网络请求
     * type为  1是修改登录密码  2是交易密码
     */
    private void loginRequest(String type) {
        dg = UIManager.getLoadingDialog(this);
        dg.setCanceledOnTouchOutside(false);
        dg.show();
        User user = AccountManager.getInstance().getUser();
        if (user != null) {
            final Map<String, String> parameters = DataHandler.getParameters("1004");
            parameters.put("id", user.getCurrUser().getSign());
            parameters.put("oldPasswd", DataHandler.encrypt3DES(oldPasswd));
            parameters.put("passwd", DataHandler.encrypt3DES(passwd));
            parameters.put("type", type);
            JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedRespon, error);
            requen.add(request);
        }
    }

    private Response.ErrorListener error = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            dg.dismiss();
            DataHandler.errorHandler(ActivityChangPsword.this, error);
        }
    };

    private Response.Listener<JSONObject> succeedRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            L.i("修改密码结果" + jobj.toString());
            dg.dismiss();
            if (JSONManager.getError(jobj) == -1) {
                //清空数据
                SharedPreferencesUtils.deleteUserInfo(ActivityChangPsword.this);
                SharedPreferencesUtils.deletePwdBoolean(ActivityChangPsword.this);
                //跳转到重新登录
                ActivityManager.getInstance().exitActivity();
                Toast.makeText(ActivityChangPsword.this,"密码修改成功，请重新登录！",Toast.LENGTH_LONG).show();
            } else {
                tv_error_hint1.setVisibility(View.VISIBLE);
                tv_error_hint1.setText(JSONManager.getMsg(jobj));
            }
        }
    };

    TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
        }

        @Override
        public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {

            oldPasswd = et_pw.getText().toString();
            passwd = et_set_pw.getText().toString();
            String str = stringFilter(oldPasswd);
            String str1 = stringFilter(passwd);
            if(!oldPasswd.equals(str)){
                et_pw.setText(str);
                et_pw.setSelection(str.length()); //光标置后
            }
            if(!passwd.equals(str1)){
                et_set_pw.setText(str1);
                et_set_pw.setSelection(str1.length()); //光标置后
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            oldPasswd = et_pw.getText().toString();
            passwd = et_set_pw.getText().toString();
            passwd1 = et_set_pw2.getText().toString();
            tv_error_hint2.setVisibility(View.GONE);
            tv_error_hint1.setVisibility(View.GONE);

            if (passwd.length() > 12) {
                register_bt.setEnabled(false);
                tv_error_hint2.setVisibility(View.VISIBLE);
                tv_error_hint2.setText("密码长度应为6-12位字符");
            } else if (!passwd1.equals("")) {
                if (passwd.length() < 6) {
                    register_bt.setEnabled(false);
                    tv_error_hint2.setVisibility(View.VISIBLE);
                    tv_error_hint2.setText("密码长度应为6-12位字符");
                } else {
                    if (!oldPasswd.equals("")) {
                        register_bt.setEnabled(true);
                    }else {
                        register_bt.setEnabled(false);
                    }
                }
            }
        }
    };

    public static String stringFilter(String str)throws PatternSyntaxException {
//        String regEx = "[/\\:*?<>|\"\n\t]"; //要过滤掉的字符
        String regEx = "[\t]"; //要过滤掉的字符
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }
}
